import hx.display.MovieClip;
import MovieClipJsonLoader.AnimateData;
import haxe.io.Path;
import hx.assets.Assets;
import hx.gemo.Rectangle;
import MovieClipJsonLoader.MovieClipJsonLoaderData;
import hx.display.BitmapData;
import hx.assets.Atlas;

using Reflect;

class JsonAtlas extends Atlas {
	public var assets:Assets;

	public var data:MovieClipJsonLoaderData;

	public function new(assets:Assets, json:MovieClipJsonLoaderData) {
		super(null);
		this.assets = assets;
		this.data = json;
		// 开始解析动画名
		for (index => array in json.frames) {
			var id = Path.withoutDirectory(Path.withoutExtension(json.images[Std.int(array[4])]));
			var bitmapData = assets.getBitmapData(id);
			var sub = bitmapData.sub(array[0], array[1], array[2], array[3]);
			sub.frameRect = new Rectangle(array[5], array[6], array[2], array[3]);
			this.bitmapDatas.set("_" + index, sub);
			this.names.push("_" + index);
		}
	}

	/**
	 * 创建动画对象
	 * @return Player
	 */
	public function createPlayer():Player {
		var player = new Player();
		for (key in data.animations.fields()) {
			var animateData:AnimateData = data.animations.getProperty(key);
			var speed = animateData.speed;
			var mc = new MovieClip();
			mc.useFrameRect = false;
			for (frame in animateData.frames) {
				mc.addFrame(this.bitmapDatas.get("_" + frame), 1 / this.data.framerate * speed);
			}
			player.animates.set(key, mc);
		}
		return player;
	}
}
